/**
 * CurdGrid对象
 * @since 1.0 <2015-6-8> SoChishun Added.
 * @since 2.0 <2015-6-11> SoChishun 重构为类对象
 * @since 2.1 <2015-6-15> SoChishun 编辑表单改为iframe方式
 */
var CurdGrid = {
    newInstance: function () {
        var obj = {
            /**
             * 对话框计数器
             */
            dialog_count: 0,
            /**
             * 默认设置
             * @type JSON
             * @since 1.0 2015-6-9 SoChishun Added.
             */
            base_config: {
                datagrid_id: '#main_grid',
                datagrid_queryParams_id: '',
                datagrid_empty_message: '', // 如：抱歉,没有数据!
                search_dialog_id: '#dlg_search',
            },
            /**
             * 表格配置
             * @type JSON
             * @since 1.0 2015-6-8 SoChishun Added.
             */
            datagrid_config: {height:480, rownumbers: true, pagination: true, pageSize: 20, singleSelect: false, checkOnSelect: true, selectOnCheck: true, onLoadError: function () {
                    if (obj.base_config.datagrid_empty_message) {
                        alert(obj.base_config.datagrid_empty_message);
                    }
                }},
            /**
             * 表格设置
             * @param JSON options
             * @since 1.0 2015-6-9 SoChishun Added.
             */
            set_datagrid_config: function (options) {
                $.extend(this.datagrid_config, options);
            },
            /**
             * 查询处理方法
             * @since 1.0 2015-6-9 SoChishun Added.
             */
            search_handler: function () {
                var data = $(this.base_config.search_dialog_id + ' form').serializeArray();
                var param = {};
                for (var i = 0; i < data.length; i++) {
                    param[data[i].name] = data[i].value;
                }
                $(this.base_config.datagrid_id).datagrid({
                    queryParams: param
                });
            },
            /**
             * 删除记录处理方法
             * @param string url
             * @since 1.0 2015-6-9 SoChishun Added.
             * @since 2.0 2015-7-1 SoChishun 把参数url改为options, 新增confim和prompt确认逻辑
             * @since 2.1 2015-7-3 SoChishun 修正prompt取消的时候会弹出错误提示的问题
             * @since 2.2 2015-7-10 SoChishun 新增成功后调用的js方法 <a data-success-fn="show_reload_tip" />
             * @since 2.3 <2015-7-28> SoChishun 新增自定义值的键名功能 <a data-value-key="id" />
             */
            delete_record_handler: function (options) {
                if (!options || !options.url) {
                    alert('方法参数无效!');
                    return;
                }
                var checks = $(obj.base_config.datagrid_id).datagrid('getChecked');
                if (checks.length < 1) {
                    alert('没有选择任何记录!');
                    return false;
                }
                var config = {
                    url: '',
                    value_key: 'id',
                    confirm_message: '', // 您确定要删除{n}条记录吗?
                    prompt_text: '', // 请输入口令
                    prompt_value: '',
                    prompt_default: '',
                    success: function () {

                    },
                }
                $.extend(config, options);
                if (config.confirm_message && !confirm(config.confirm_message.replace('{n}', checks.length))) {
                    return;
                }
                if (config.prompt_text) {
                    var code = prompt(config.prompt_text, config.prompt_default);
                    if (null === code) {
                        return;
                    }
                    if (code != config.prompt_value) {
                        alert('输入错误!');
                        return;
                    }
                }
                var ids = '';
                $(checks).each(function () {
                    ids += ',' + this[config.value_key];
                })
                ids = ids.substring(1);
                config.url = config.url.replace('varid', ids).replace('varkey', ids);
                this.ajax_get_process({url: config.url, success: config.success});
            },
            /**
             * ajax普通处理
             * @param string url
             * @since 1.0 <2015-6-26> SoChishun Added.
             * @since 1.1 <2015-7-10> SoChishun 参数url改为选项形式,新增options.success选项
             */
            ajax_get_process: function (options) {
                if (!options || !options.url) {
                    alert('[ajax_get_process] 无效参数!');
                    return;
                }
                // 显示loading
                var $grid = $(this.base_config.datagrid_id);
                if (!$grid.children("div.datagrid-mask").length) {
                    $('<div class="datagrid-mask" style="display:block"></div>').appendTo($grid);
                    var $msg = $('<div class="datagrid-mask-msg" style="display:block;left:50%"></div>').html('正在处理...').appendTo($grid);
                    $msg._outerHeight(40);
                    $msg.css({marginLeft: (-$msg.outerWidth() / 2), lineHeight: ($msg.height() + "px")});
                }
                $.ajax({
                    type: 'GET',
                    dataType: 'JSON',
                    url: options.url,
                    success: function (msg) {
                        $grid.children("div.datagrid-mask-msg, div.datagrid-mask").remove();
                        if (msg.status) {
                            options.success();
                            $(obj.base_config.datagrid_id).datagrid('reload');
                        } else {
                            alert(msg.info);
                        }
                    },
                    error: function () {
                        $grid.children("div.datagrid-mask-msg, div.datagrid-mask").remove();
                        $.messager.alert('警告', '抱歉,操作提交失败,请联系管理员!', 'warning');
                    },
                });
            },
            /**
             * 打开查询对话框前的操作
             * @since 1.0 <2015-6-30> SoChishun Added.
             */
            before_search_dialog: function () {
            },
            /**
             * curd按钮点击设置
             * @since 1.0 2015-6-10 SoChishun Added.
             */
            link_click_handler: function () {
                // 查询按钮
                $(".lnk_grid_search").click(function () {
                    return obj.lnk_search_event(this);
                });
                // 新增按钮
                $(".lnk_grid_add").click(function () {
                    return obj.lnk_add_event(this);
                });
                // 编辑按钮
                $(".lnk_grid_edit").click(function () {
                    return obj.lnk_edit_event(this);
                });
                // 删除按钮
                $(".lnk_grid_remove").click(function () {
                    return obj.lnk_remove_event(this);
                });
                // 普通后台操作按钮
                $('.lnk_grid_process').click(function () {
                    return obj.lnk_process_event(this);
                });
                // 普通展示按钮
                $('.lnk_grid_info').click(function () {
                    return obj.lnk_info_event(this);
                })
            },
            /**
             * 查询事件
             * @param element a
             * @since 1.0 <2015-7-8> SoChishun Added.
             */
            lnk_search_event: function (a) {
                this.before_search_dialog();
                this.open_search_dialog();
                return false;
            },
            /**
             * 添加事件
             * @param element a
             * @since 1.0 <2015-7-8> SoChishun Added.
             * @since 1.1 <2015-7-25> SoChishun 新增图标同步功能.
             */
            lnk_add_event: function (a) {
                var $a = $(a);
                this.open_iframe_dialog({title: $a.text(), icon: $a.attr('iconCls'), url: $a.attr('href')});
                return false;
            },
            /**
             * 编辑事件
             * @param element a
             * @since 1.0 <2015-7-8> SoChishun Added.
             * @since 1.1 <2015-7-10> SoChishun 取消多选只能编辑第一条的限制
             * @since 1.2 <2015-7-25> SoChishun 新增图标同步功能.
             * @since 1.3 <2015-7-28> SoChishun 新增自定义值的键名功能 <a data-value-key="id" />
             */
            lnk_edit_event: function (a) {
                var checks = $(this.base_config.datagrid_id).datagrid('getChecked');
                if (checks.length < 1) {
                    alert('没有选择任何记录!');
                    return false;
                }
                if (checks.length > 1) {
                    alert('您选择了' + checks.length + '条记录进行编辑.\n(弹窗太多会使浏览器变卡,请及时关闭无用的弹窗.)');
                }
                var $a = $(a);
                var value_key = $a.data('valueKey') ? $a.data('valueKey') : 'id';
                $(checks).each(function () {
                    obj.open_iframe_dialog({title: $a.text(), icon: $a.attr('iconCls'), url: $a.attr('href').replace('varid', this[value_key]).replace('varkey', this[value_key])});
                })
                return false;
            },
            /**
             * 删除事件
             * @param element a
             * @since 1.0 <2015-7-8> SoChishun Added.
             * @since 1.1 <2015-7-10> SoChishun 新增成功后调用的js方法 <a data-success-fn="show_reload_tip" />
             * @since 1.2 <2015-7-28> SoChishun 新增自定义值的键名功能 <a data-value-key="id" />
             */
            lnk_remove_event: function (a) {
                var $a = $(a);
                var options = {
                    url: $a.attr('href'),
                    value_key: $a.data('valueKey') ? $a.data('valueKey') : 'id',
                    confirm_message: $a.data('confirmMessage'), // 您确定要删除这{n}条记录吗?
                    prompt_text: $a.data('promptText'), // 请输入口令
                    prompt_value: $a.data('promptValue'),
                    prompt_default: $a.data('promptDefault'),
                    success: function () {
                        var success_fn = $a.data('successFn');
                        if (success_fn) {
                            if (success_fn.indexOf('(') < 0) {
                                success_fn += '()';
                            }
                            eval(success_fn);
                        }
                    }
                }
                if (!options.confirm_message) {
                    options.confirm_message = '您确定要删除这{n}条记录吗?';
                }
                if (options.prompt_value && !options.prompt_text) {
                    options.prompt_text = '请输入口令：';
                }
                this.delete_record_handler(options);
                return false;
            },
            /**
             * 后台处理事件
             * <br />与lnk_remove_event不同在于不需要勾选grid行
             * @param element a
             * @since 1.0 <2015-7-8> SoChishun Added.
             * @since 1.0 <2015-7-10> SoChishun 新增成功后调用的js方法 <a data-success-fn="show_reload_tip" />
             */
            lnk_process_event: function (a) {
                var $a = $(a);
                obj.ajax_get_process({url: $a.attr('href'), success: function () {
                        var success_fn = $a.data('successFn');
                        if (success_fn) {
                            if (success_fn.indexOf('(') < 0) {
                                success_fn += '()';
                            }
                            eval(success_fn);
                        }
                    }});
                return false;
            },
            /**
             * 信息事件
             * <br />与lnk_add_event弹窗类似，但没有按钮组，纯粹展示页面
             * @param element a
             * @since 1.0 <2015-7-8> SoChishun Added.
             * @since 1.1 <2015-7-10> SoChishun 新增data-need-checking参数 <a data-need-checking="true" />
             * @since 1.2 <2015-7-24> SoChishun 新增size参数和noheader参数 <a data-size='"width":600' data-noheader="true" />
             * @since 1.3 <2015-7-25> SoChishun 新增图标同步功能.
             * @since 1.4 <2015-7-28> SoChishun 新增自定义值的键名功能 <a data-value-key="id" />
             * @example <a href="{:U('Statics/call_history_lite','queue='.$key)}" class="lnk_info" data-size='"width":600' data-noheader="true">[通话详单]</a>
             */
            lnk_info_event: function (a) {
                var $a = $(a);
                try {
                    var size = $a.data('size') ? JSON.parse('{' + $a.data('size') + '}') : undefined;
                } catch (e) {
                    alert('lnk_info_event: ' + e.message);
                    return false;
                }
                var noheader = $a.data('noheader');
                var url = $a.attr('href');
                var title = $a.data('title') ? $a.data('title') : $a.text();
                var needChecking = $a.data('needChecking');
                if (needChecking) {
                    var value_key = $a.data('valueKey') ? $a.data('valueKey') : 'id';
                    var checks = $(this.base_config.datagrid_id).datagrid('getChecked');
                    if (checks.length < 1) {
                        alert('没有选择任何记录!');
                        return false;
                    }
                    $(checks).each(function () {
                        obj.open_iframe_dialog({title: title, icon: $a.attr('iconCls'), noheader: noheader, url: url.replace('varid', this[value_key]).replace('varkey', this[value_key])}, size);
                    })
                } else {
                    this.open_iframe_dialog({title: title, icon: $a.attr('iconCls'), noheader: noheader, url: url, buttons: []}, size);
                }
                return false;
            },
            /**
             * 初始化
             * @param JSON options
             * @since 1.0 2015-6-8 SoChishun Added.
             */
            init: function (options) {
                if (undefined != options) {
                    $.extend(this.base_config, options);
                }
                // 初始化grid
                if (this.base_config.datagrid_id && this.datagrid_config) {
                    var $grid = $(this.base_config.datagrid_id);
                    if (!this.datagrid_config.url) {
                        this.datagrid_config.url = $grid.data('url');
                    }
                    // 读取grid中的data-queryParams
                    if ($grid.data('queryParams')) {
                        this.datagrid_config.queryParams = $.parseJSON('{' + $grid.data('queryParams') + '}');
                    }
                    // 读取隐藏配置 datagrid_queryParams_id
                    if (this.base_config.datagrid_queryParams_id) {
                        this.datagrid_config.queryParams = $.parseJSON('{' + $(this.base_config.datagrid_queryParams_id).html() + '}');
                    }
                    //TODO: 设置pagination:true的时候,会触发重复加载数据源的BUG,待解决
                    $grid.datagrid(this.datagrid_config);
                }
                // 初始化按钮点击事件
                this.link_click_handler();
            },
            /**
             * 刷新表格
             * @param object param
             * @since 1.0 <2015-7-6> SoChishun Added.
             */
            reload_grid: function (param) {
                if (param) {
                    $(this.base_config.datagrid_id).datagrid({queryParams: param});
                } else {
                    $(this.base_config.datagrid_id).datagrid('reload');
                }
            },
            /**
             * 打开新增/编辑对话框
             * @param string url
             * @since 1.0 <2015-6-9> SoChishun Added.
             * @since 2.0 <2015-6-16> SoChishun 重构为iframe
             * @since 2.1 <2015-6-25> SoChishun 新增onClose方法,释放资源
             * @since 2.2 <2015-7-24> SoChishun 新增size参数和noheader参数
             */
            open_iframe_dialog: function (param, size) {
                if (!param || !param.url) {
                    alert('对话框参数有误!');
                    return;
                }
                var ifrm_id = 'editform_' + this.dialog_count;
                this.dialog_count++;
                var _param = {url: '', title: '编辑表单', icon: 'icon-edit', buttons: [{
                            text: '保存',
                            iconCls: 'icon-ok',
                            handler: function () {
                                // 子页面要有item_form实例对象
                                if (undefined == $('#' + ifrm_id)[0].contentWindow.item_form) {
                                    alert('未设置表单提交处理方法!');
                                } else {
                                    $('#' + ifrm_id)[0].contentWindow.item_form.submit(ifrm_id);
                                }

                            }
                        }, {
                            text: '重置',
                            iconCls: 'icon-undo',
                            handler: function () {
                                $('#' + ifrm_id).contents().find("form").form('reset');
                            }
                        }, {
                            text: '取消',
                            iconCls: 'icon-cancel',
                            handler: function () {
                                obj.close_iframe_dialog(ifrm_id);
                            }
                        }]};
                $.extend(_param, param);
                var config = {
                    title: _param.title,
                    iconCls: _param.icon,
                    noheader: _param.noheader,
                    resizable: true,
                    onClose: function () {
                        var $dlg = $('#' + ifrm_id).attr('src', "about:blank").parent();
                        $dlg.next().remove();
                        $dlg.remove();
                        $dlg = null;
                    },
                    buttons: _param.buttons,
                };
                if (size) {
                    if (size.width) {
                        config.width = size.width;
                    }
                    if (size.height) {
                        config.height = size.height;
                    }
                }
                $('<iframe id="' + ifrm_id + '" name="' + ifrm_id + '"></iframe>').dialog(config);
                $('#' + ifrm_id).attr('src', _param.url).load(function () {
                    obj.resize_iframe_dialog(ifrm_id, size);
                });
            },
            /**
             * 关闭IFrame对话框
             * @param string ifrm_id
             * @since 1.0 <2015-6-16> SoChishun Added.
             */
            close_iframe_dialog: function (ifrm_id, refresh) {
                var $dlg = $('#' + ifrm_id).attr('src', "about:blank").dialog('close').parent();
                $dlg.next().remove();
                $dlg.remove();
                $dlg = null;
                if (refresh) {
                    $(obj.base_config.datagrid_id).datagrid('reload');
                }
            },
            /**
             * 重设IFrame对话框尺寸
             * @param string ifrm_id
             * @param object o_size
             * @since 1.0 <2015-6-16> SoChishun Added.
             * @since 1.1 <2015-6-25> SoChishun 新增size
             * @example window.parent.curd_grid.resize_iframe_dialog(window.name,{width:332});
             */
            resize_iframe_dialog: function (ifrm_id, size) {
                var $ifrm = $('#' + ifrm_id);
                var _size = {
                    height: $ifrm.contents().find("body").height(),
                    width: $ifrm.contents().find("body").width()
                };
                if (size) {
                    $.extend(_size, size);
                }
                $ifrm.dialog({height: _size.height + 100, width: _size.width + 20});
            },
            /**
             * 打开查询对话框
             * @since 1.0 <2015-6-9> SoChishun Added
             * @since 1.1 <2015-6-30> SoChishun 新增导出按钮功能(在form新增data-export-url属性即可)
             */
            open_search_dialog: function () {
                var config = {
                    title: '搜索',
                    iconCls: 'icon-search',
                    buttons: [{
                            text: '确定',
                            iconCls: 'icon-ok',
                            handler: function () {
                                obj.search_handler();
                                $(obj.base_config.search_dialog_id).dialog('close');
                            }
                        }, {
                            text: '重置',
                            iconCls: 'icon-undo',
                            handler: function () {
                                $(obj.base_config.search_dialog_id + ' form').form('reset');
                            }
                        }, {
                            text: '取消',
                            iconCls: 'icon-cancel',
                            handler: function () {
                                $(obj.base_config.search_dialog_id).dialog('close');
                            }
                        }]
                };
                var $form = $(this.base_config.search_dialog_id).find("form");
                if ($form.data('exportUrl')) {
                    config.buttons.splice(2, 0, {
                        text: '导出',
                        iconCls: 'icon-save',
                        handler: function () {
                            var action = $form.attr('action');
                            $form.attr('action', $form.data('exportUrl')).submit();
                            $form.attr('action', action);
                        }
                    });
                }
                $(this.base_config.search_dialog_id).dialog(config);
            },
        };
        return obj;
    }
}